package com.yshebkb.sulp.dao;

import com.yshebkb.sulp.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author yshebkb
 */
@Repository
@Mapper
public interface UserMapper {
    @Delete({
            "delete from user",
            "where id = #{id,jdbcType=BIGINT}"
    })
    int deleteByPrimaryKey(Long id);

    @Insert({
            "insert into user (id, name, ",
            "chsname, email, ",
            "password, status, ",
            "create_time, update_time)",
            "values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, ",
            "#{chsname,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, ",
            "#{password,jdbcType=VARCHAR}, #{status,jdbcType=TINYINT}, ",
            "#{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP})"
    })
    int insert(User record);

    int insertSelective(User record);

    @Select("select * from user where id = #{id}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "roles", column = "id",
                    many = @Many(select = "com.yshebkb.sulp.dao.RoleMapper.selectAllRoles",
                            fetchType = FetchType.LAZY))
    })
    User selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(User record);

    @Update({
            "update user",
            "set name = #{name,jdbcType=VARCHAR},",
            "chsname = #{chsname,jdbcType=VARCHAR},",
            "email = #{email,jdbcType=VARCHAR},",
            "password = #{password,jdbcType=VARCHAR},",
            "status = #{status,jdbcType=TINYINT},",
            "create_time = #{createTime,jdbcType=TIMESTAMP},",
            "update_time = #{updateTime,jdbcType=TIMESTAMP}",
            "where id = #{id,jdbcType=BIGINT}"
    })
    int updateByPrimaryKey(User record);

    @Select("select * from user where name=#{name}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "roles", column = "id",
                    many = @Many(select = "com.yshebkb.sulp.dao.RoleMapper.selectAllRoles",
                            fetchType = FetchType.LAZY))
    })
    User findByName(String name);

    @Select("select * from user")
    List<User> findAll();

    @Select("select * from user where id in (select user_role.user_id from user_role where user_role.role_id=#{id})")
    List<User> selectAllUsers(Long id);
}